package cn.tedu.tourism.user.service.impl;

import cn.tedu.tourism.base.exception.ServiceException;
import cn.tedu.tourism.base.response.StatusCode;
import cn.tedu.tourism.user.mapper.UserMapper;
import cn.tedu.tourism.user.pojo.dto.UserLogin;
import cn.tedu.tourism.user.pojo.dto.UserReg;
import cn.tedu.tourism.user.pojo.entity.User;
import cn.tedu.tourism.user.pojo.vo.UserVO;
import cn.tedu.tourism.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserVO login(UserLogin userLogin) {
        log.debug("用户登录业务：{}",userLogin);
        UserVO userVO = userMapper.selectByUsername(userLogin.getUsername());
        if (userVO == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if(!userVO.getPassword().equals(userLogin.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

    @Override
    public void register(UserReg userReg) {
        log.debug("保存用户业务：{}",userReg);
        User user = new User();
        BeanUtils.copyProperties(userReg,user);
        if (user.getId()==null){
            user.setCreateTime(new Date());
            user.setRegistrationDate(new Date());
            userMapper.insert(user);
        }else{
            //如果有用户id，说明是修改操作
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }


    }

    @Override
    public List<UserVO> selectById(Integer id) {
        log.debug("查询用户信息业务：{}",id);
        List<UserVO> list = userMapper.selectById(id);
        return list;
    }

    @Override
    public UserVO selectByUsername(String username) {
        log.debug("查询用户名是否已存在业务：{}",username);
        UserVO userVO = userMapper.selectByUsername(username);
        log.debug("查询结果：{}",userVO);
        if (userVO!=null){
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        return userVO;
    }

}
